package dao

import (
	"time"
	"user_srv/model"
	"user_srv/user"
)

// 创建签到记录
func CreateSignRecord(in *user.SignInRequest) (*model.SignRecord, error) {
	record := &model.SignRecord{
		UserId:   uint(in.UserId), // 从请求中获取用户ID
		SignDate: time.Now(),      // 当前时间作为签到日期
		Points:   10,              // 签到积分，可从配置读取
	}

	// 调用 model 层定义的结构体方法 CreateRecord，插入数据库
	err := record.CreateRecord()
	if err != nil {
		return nil, err // 插入失败，返回错误
	}

	// 插入成功，返回创建的记录
	return record, nil
}

// 查询用户签到列表（分页）
func GetSignList(userID int64, page int32, size int32) ([]model.SignRecord, int64, error) {
	var sr model.SignRecord
	offset := int((page - 1) * size)
	limit := int(size)
	return sr.GetSignListByUserID(userID, offset, limit)
}

// 补签
func RetroactiveSign(userID int64) (bool, int32, string, error) {
	date := time.Now()

	sr := model.SignRecord{
		UserId:   uint(userID),
		SignDate: date,
	}

	// 检查是否已签到
	exists, err := sr.CheckDateExists()
	if err != nil {
		return false, 0, "查询失败", err
	}
	if exists {
		return false, 0, "该日已签到", nil
	}

	// 插入补签记录
	record := &model.SignRecord{
		UserId:   uint(userID),
		SignDate: date,
		Points:   5, // 补签积分，可从配置读取
	}
	err = record.CreateRecord()
	if err != nil {
		return false, 0, "补签失败", err
	}

	return true, int32(record.Points), "补签成功", nil
}

// 位图 获取用户连续签到天数
func GetContinuousSignDays(userID int64) (int32, error) {
	sr := model.SignRecord{UserId: uint(userID)}
	return sr.GetContinuousDays()
}

// 标记用户签到
func MarkBitmapSignIn(userID int64) error {
	sr := model.SignRecord{UserId: uint(userID)} // 只赋值 UserId
	return sr.MarkTodayBitmap()
}

// 今天是否已签到
func IsBitmapSigned(userID int64) (bool, error) {
	sr := model.SignRecord{UserId: uint(userID)}
	return sr.IsTodayBitmapSigned()
}

// 本月连续签到天数
func GetBitmapContinuousDays(userID int64) (int, error) {
	sr := model.SignRecord{UserId: uint(userID)}
	return sr.ContinuousDaysBitmap()
}
